package com.example.android.chartapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;

public class ChartCircle extends View {
    public ChartCircle(Context context) {
        super(context);
    }

    public ChartCircle(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ChartCircle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private ArrayList<Float> datas = new ArrayList<>();
    private final static int[] COLORS = new int[] {Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.GRAY};
    private static final int  CX = 150, CY = 150, R = 135;
    private float sum = 0;
    private RectF oval = new RectF();

    public void addData(float data) {
        datas.add(data);
        if (datas.size() > 5) datas.remove(0);
        sum = 0;
        for (float d : datas) sum += d;
        postInvalidate();
    }

    Paint paint = new Paint();
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(CX, CY);
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
        oval.top = -R;
        oval.left = -R;
        oval.right = R;
        oval.bottom = R;

        canvas.drawCircle(0, 0, R, paint);

    }

    Paint contentPaint = new Paint();
    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        contentPaint.setAntiAlias(true);
        contentPaint.setStyle(Paint.Style.FILL);

        float startAngle = 0;

        for (int i = 0; i < datas.size(); i++) {
            contentPaint.setColor(COLORS[i]);

            if (datas.get(i) == 0) continue;
            float endAngle = datas.get(i) / sum * 360;

            float textX = (float) (Math.cos(Math.toRadians(startAngle + endAngle / 2)) * R * 0.6);
            float textY = (float) (Math.sin(Math.toRadians(startAngle + endAngle / 2)) * R * 0.6);

            canvas.drawArc(oval, startAngle, endAngle, true, contentPaint);
            contentPaint.setColor(Color.BLACK);
            canvas.drawText(datas.get(i) + "", textX, textY, contentPaint);

            startAngle += endAngle;
        }
    }
}
